<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="期望工作" prop="encryptExpectId">
              <el-select v-model="queryParams.encryptExpectId" placeholder="请选择期望工作" clearable>
                <el-option v-for="dict in encrypt_expect_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in execute_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker v-model="dateRangeCreateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="SwitchButton" v-hasPermi="['boss:applyJob:edit']"
              @click="initBossDialog()">初始化</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['boss:applyJob:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['boss:applyJob:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['boss:applyJob:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="applyJobList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="applyJobId" v-if="true" width="180" />
        <el-table-column label="期望工作" align="center" prop="encryptExpectId" width="80">
          <template #default="scope">
            <dict-tag :options="encrypt_expect_type" :value="scope.row.encryptExpectId" />
          </template>
        </el-table-column>
        <el-table-column label="页数" align="center" prop="pages" width="60" />
        <el-table-column label="跳过猎头" align="center" prop="skipHeadhunting" width="80">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.skipHeadhunting" />
          </template>
        </el-table-column>
        <el-table-column label="跳过兼职" align="center" prop="skipPartTimeJob" width="80">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.skipPartTimeJob" />
          </template>
        </el-table-column>
        <el-table-column label="最低薪资" align="center" prop="minSalary" width="80" />
        <el-table-column label="最高薪资" align="center" prop="maxSalary" width="80" />
        <el-table-column label="投递岗位" align="center" prop="positionName">
          <template #default="scope">
            <dict-tag :options="boss_position_name"
              :value="scope.row.positionName ? scope.row.positionName.split(',') : []" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="活跃时间" align="center" prop="activeTimeDesc">
          <template #default="scope">
            <dict-tag :options="boss_active_time_desc"
              :value="scope.row.activeTimeDesc ? scope.row.activeTimeDesc.split(',') : []" />
          </template>
        </el-table-column> -->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="execute_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="applyCount" width="80" />
        <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.finishTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['boss:applyJob:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['boss:applyJob:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改沟通任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="applyJobFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="期望工作" prop="encryptExpectId">
          <el-select v-model="form.encryptExpectId" placeholder="请选择期望工作">
            <el-option v-for="dict in encrypt_expect_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行页数" prop="pages">
          <el-input v-model="form.pages" type="number" placeholder="请输入执行页数" />
        </el-form-item>
        <el-form-item label="跳过猎头" prop="skipHeadhunting">
          <el-radio-group v-model="form.skipHeadhunting">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跳过兼职" prop="skipPartTimeJob">
          <el-radio-group v-model="form.skipPartTimeJob">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最低薪资" prop="minSalary">
          <el-input v-model="form.minSalary" type="number" placeholder="请输入最低薪资不可低于">
            <template #append>
              <span>K</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="最高薪资" prop="maxSalary">
          <el-input v-model="form.maxSalary" type="number" placeholder="请输入最高薪资不可低于">
            <template #append>
              <span>K</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="投递岗位" prop="positionName">
          <el-checkbox-group v-model="form.positionName">
            <el-checkbox v-for="dict in boss_position_name" :key="dict.value" :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="活跃时间" prop="activeTimeDesc">
          <el-checkbox-group v-model="form.activeTimeDesc">
            <el-checkbox v-for="dict in boss_active_time_desc" :key="dict.value" :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 初始化对话框 -->
    <el-dialog :title="initDialog.title" v-model="initDialog.visible" width="500px" append-to-body>
      <el-form ref="initBossFormRef" :model="initBossForm" :rules="initBossRules" label-width="80px">
        <el-form-item label="cookie" prop="cookie">
          <el-input v-model="initBossForm.cookie" placeholder="请输入cookie" />
        </el-form-item>
        <el-form-item label="zpToken" prop="zpToken">
          <el-input v-model="initBossForm.zpToken" placeholder="请输入zpToken" />
        </el-form-item>
        <el-form-item label="token" prop="token">
          <el-input v-model="initBossForm.token" placeholder="请输入token" />
        </el-form-item>
        <el-form-item label="traceId" prop="traceId">
          <el-input v-model="initBossForm.traceId" placeholder="请输入traceId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitInitBossForm">确 定</el-button>
          <el-button @click="cancelInitBoss">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ApplyJob" lang="ts">
  import { listApplyJob, getApplyJob, delApplyJob, addApplyJob, updateApplyJob, initBoss } from '@/api/boss/applyJob';
  import { ApplyJobVO, ApplyJobQuery, ApplyJobForm, InitBossForm } from '@/api/boss/applyJob/types';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { boss_active_time_desc, boss_position_name, sys_yes_no, execute_status, encrypt_expect_type } = toRefs<any>(proxy?.useDict('boss_active_time_desc', 'boss_position_name', 'sys_yes_no', 'execute_status', 'encrypt_expect_type'));

  const applyJobList = ref<ApplyJobVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

  const queryFormRef = ref<ElFormInstance>();
  const applyJobFormRef = ref<ElFormInstance>();
  const initBossFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const initDialog = reactive<DialogOption>({
    visible: false,
    title: '初始化'
  });

  const initFormData : ApplyJobForm = {
    applyJobId: undefined,
    encryptExpectId: undefined,
    pages: 20,
    skipHeadhunting: "Y",
    skipPartTimeJob: "Y",
    minSalary: 15,
    maxSalary: 18,
    positionName: ["Java"],
    activeTimeDesc: ["刚刚活跃", "今日活跃", "昨日活跃"],
    status: undefined,
    applyCount: undefined,
    finishTime: undefined,
  }

  const initInitBossFormData : InitBossForm = {
    cookie: undefined,
    zpToken: undefined,
    token: undefined,
    traceId: undefined,
  }

  const initBossForm = ref({ ...initInitBossFormData });

  const initBossRules = {
    cookie: [
      { required: true, message: "cookie不能为空", trigger: "blur" }
    ],
    zpToken: [
      { required: true, message: "zpToken不能为空", trigger: "blur" }
    ],
    token: [
      { required: true, message: "token不能为空", trigger: "blur" }
    ],
    traceId: [
      { required: true, message: "traceId不能为空", trigger: "blur" }
    ],
  }

  const data = reactive<PageData<ApplyJobForm, ApplyJobQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      orderByColumn: 'applyJobId',
      isAsc: 'desc',
      encryptExpectId: undefined,
      status: undefined,
      params: {
        createTime: undefined,
      }
    },
    rules: {
      applyJobId: [
        { required: true, message: "id不能为空", trigger: "blur" }
      ],
      encryptExpectId: [
        { required: true, message: "期望工作不能为空", trigger: "change" }
      ],
      pages: [
        { required: true, message: "执行页数不能为空", trigger: "blur" }
      ],
      skipHeadhunting: [
        { required: true, message: "跳过猎头不能为空", trigger: "change" }
      ],
      skipPartTimeJob: [
        { required: true, message: "跳过兼职不能为空", trigger: "change" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询沟通任务列表 */
  const getList = async () => {
    loading.value = true;
    queryParams.value.params = {};
    proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
    const res = await listApplyJob(queryParams.value);
    applyJobList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  const initBossDialog = () => {
    resetInitBoss();
    initDialog.visible = true;
  }

  const cancelInitBoss = () => {
    resetInitBoss();
    initDialog.visible = false;
  }

  const submitInitBossForm = () => {
    initBossFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        await initBoss(initBossForm.value).finally(() => buttonLoading.value = false);
        proxy?.$modal.msgSuccess("操作成功");
        initDialog.visible = false;
      }
    });
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    applyJobFormRef.value?.resetFields();
  }

  /** 表单重置 */
  const resetInitBoss = () => {
    initBossForm.value = { ...initInitBossFormData };
    initBossFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    dateRangeCreateTime.value = ['', ''];
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : ApplyJobVO[]) => {
    ids.value = selection.map(item => item.applyJobId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加沟通任务";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: ApplyJobVO) => {
    reset();
    const _applyJobId = row?.applyJobId || ids.value[0]
    const res = await getApplyJob(_applyJobId);
    Object.assign(form.value, res.data);
    form.value.positionName = form.value.positionName.split(",");
    form.value.activeTimeDesc = form.value.activeTimeDesc.split(",");
    dialog.visible = true;
    dialog.title = "修改沟通任务";
  }

  /** 提交按钮 */
  const submitForm = () => {
    applyJobFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        form.value.positionName = form.value.positionName.join(",");
        form.value.activeTimeDesc = form.value.activeTimeDesc.join(",");
        if (form.value.applyJobId) {
          await updateApplyJob(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addApplyJob(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: ApplyJobVO) => {
    const _applyJobIds = row?.applyJobId || ids.value;
    await proxy?.$modal.confirm('是否确认删除沟通任务编号为"' + _applyJobIds + '"的数据项？').finally(() => loading.value = false);
    await delApplyJob(_applyJobIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('boss/applyJob/export', {
      ...queryParams.value
    }, `applyJob_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>
